var _ = require('lodash'),
    Post = require('./post.model'),
    im = require('immutable'),
    faker = require('faker');


const DEFAULT_PAGESIZE = 10,
    MIN_PAGESIZE = 5,
    MAX_PAGESIZE = 25;

// Get list of posts
exports.index = function(req, res) {
    // if(req.query.page && req.query.page < 1) return res.status(400).send('Invalid page');

    // Parse the page size that client pass in
    var pageSize = (req.query.pagesize && req.query.pagesize <= MAX_PAGESIZE && req.query.pagesize > MIN_PAGESIZE) ? req.query.pagesize : DEFAULT_PAGESIZE;
    var page = parseInt(req.query.page) || 0;
    if (page < 1) page = 1;

    Post.count({}, function(err, count) {
        // if(err) return util.handleError(res, err);
        var query;
        query = Post.find();
        query
            .limit(pageSize)
            .sort('date')
            .skip((page-1) * pageSize || 0)//doesn't scale well, I'll worry about it later
            .exec(function(err, posts) {
                // if(err) return util.handleError(res, err);
                setTimeout(function() {
                    return res.status(200).json({
                            page: page,
                            pages: Math.ceil(count / pageSize),
                            items: posts,
                            numItems: count
                         });
                },300);

            });
    });
};

exports.faker = function(req, res) {
    
    var fakeItems = im.Range(1,100)
      .map( () => { 
        return new Post({ title: faker.name.findName() });
      });


    Post.insertMany(fakeItems, function(error, docs) {

        if (error) {
            return res.status(400).json({
                error_info: error,
            });
        } else {
            console.info('%d items were successfully stored.', docs.length);
            return res.status(200).json({
                items: fakeItems,
            });
        }

    });

};




// Get list of posts
exports.auth = function(req, res) {
    res.status(200).json({
                auth: "you have logged in to see this"
    });
};



